<?php
namespace App\Http\Middleware;

use App\Models\AdminLog;
use App\Models\User;
use App\Services\PermissionService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Facades\Agent;

class AdminOperationLog
{
    /**
     * 后置：请求后写入操作日志
     * @param Request $request
     * @param Closure $next
     * @param string $type // 日志类型：basic操作日志 ，login登录日志
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $type = '')
    {
        $user = Auth::user();
        $response = $next($request);
//        if (app()->isProduction() && Auth::check() && in_array($request->method(), [])) {
        if ($request->method() != 'GET' && in_array($type, ['basic', 'login'])) {
            try {
                $route = $request->route();// 当前路由信息
                $action = $route->getActionName(); // 控制器（含方法）
                $routeAsName = $route->getName() ?: ""; // 路由别名
                list($actionController, $actionMethod) = explode("@", $action);
                $responseContent = $response->getContent(); // 响应内容
                $responseContentToArray = json_decode($responseContent, true);
                $replaceSensitive = ['password' => '******', 'password_confirmation'=>'******', 'token' => '******']; // 替换敏感词
                $responseContentToArray = arrayReplaceRecursive($responseContentToArray, $replaceSensitive);
                $getActionMethodName = PermissionService::getPermissionNameByPriv($routeAsName); // 获取操作行为
                $actionDescription = $getActionMethodName ?: $routeAsName; // 操作描述
                $log_id = $responseContentToArray['e_code'] ?? 0; // 操作异常情况先记录日志，前端暴露e_code给予用户而不露真实错误message，后在补充日志信息
                // 日志信息==========
                $adminLog = new AdminLog();
                if ($log_id > 0) {
                    $adminLog = AdminLog::find($log_id);
                }
                $adminLog->type = $type; // 日志类型
                $requestParameters = $request->all(); // 请求参数
                $requestParameters = arrayReplaceRecursive($requestParameters, $replaceSensitive);
                $adminLog->request_parameters = json_encode($requestParameters, JSON_UNESCAPED_UNICODE);
                // 管理员信息
                $admin_name = $user->name ?? '';
                $admin_username = $user->username ?? '';
                $admin_id = $user->id ?? 0;
                if ($type == 'login') {
                    $tmpUser = User::where('username', $requestParameters['username'])->first();
                    $admin_name = $tmpUser->name ?? '';
                    $admin_username = $tmpUser->username ?? $requestParameters['username'];
                    $admin_id = $tmpUser->id ?? 0;
                }
                $adminLog->admin_username = $admin_username;
                $others = $request->info_category ? "。" . __('infoCategory.category') . "：" . $request->info_category->name . '-ID:' . $request->info_category->id : '';
                // $adminLog->content = __('adminLog.action_content', ['admin_name' => $admin_name, 'admin_username' => $admin_username ? "（{$admin_username}）" : '', 'action_description' => $actionDescription, 'others' => $others]);
                $adminLog->content = __('adminLog.action_content', ['admin_name' => $admin_name, 'admin_username' => '', 'action_description' => $actionDescription, 'others' => $others]);
                $adminLog->request_uri = $request->path();
                $adminLog->request_method = $request->method();
                $adminLog->request_ip = $request->ip();
                $adminLog->request_user_agent = $request->userAgent();
                $adminLog->request_browser = Agent::browser();
                $adminLog->request_platform = Agent::platform();
                $adminLog->request_browser_version = Agent::version($adminLog->request_browser);
                $adminLog->request_platform_version = Agent::version($adminLog->request_platform);
                $adminLog->action = $action;
                $adminLog->action_controller = $actionController;
                $adminLog->action_controller_name = PermissionService::getModuleNameByController($actionController); // 模块名称
                $adminLog->action_method = $actionMethod;
                $adminLog->action_method_name = $getActionMethodName ?: $actionMethod;
                $adminLog->route_as_name = $routeAsName;
                $adminLog->created_user_id = $admin_id;
                $adminLog->response = json_encode($responseContentToArray, JSON_UNESCAPED_UNICODE); // 响应内容
                $adminLog->status = $responseContentToArray['status'] ?? 0;
                $adminLog->save();
            } catch (\Exception $exception) {
            }
        }
        return $response;
    }
}
